from _ast import In
import pandas as pd
import numpy as np

'''
序列化和反序列化方法
'''
df = pd.DataFrame({
    'name':['zhangsan' , 'lisi' , 'wangwu'],
    'age':[21,40,23],
    'sex':['male' , 'female' , 'male'],
})

#把DataFrame序列化成一个csv文件
df.to_csv('data.csv' , index=False)

new_df = pd.read_csv('data.csv')
# print(new_df)

'''
数据筛选和排序
'''
#sex包含'male'的行
male_df = new_df[new_df['sex'] == 'male']

#将行按'age'升序排列
sorted_df = new_df.sort_values(by='age')

# print(male_df)
# print(sorted_df)

"""
合并和连接数据
"""
df1 = pd.DataFrame({
    'id':[0,1,2],
    'name':['zhangsan' , 'lisi' , 'wangwu'],
})

df2 = pd.DataFrame({
    'id':[0,1,2],
    'age':[21,40,23],
})
#基于id 合并两个DataFrame
merged_df = pd.merge(df1, df2, on='id')

#垂直叠加两个DataFrame
concat_df = pd.concat([df1,df2] , axis=1)

# print(merged_df)
# print(concat_df)

dates = pd.date_range("20180101", periods=6)
# print(dates)
df2 = pd.DataFrame(np.random.randn(6,4) , index=dates , columns=list('abcd'))
'''
                   a         b         c         d
2018-01-01 -0.503270 -0.791632 -1.619768  0.959107
2018-01-02  1.018737 -1.255549  0.470029  3.414918
2018-01-03  1.087138  0.219530 -0.005590  0.884475
2018-01-04 -0.526701 -1.637120 -1.816465  0.517950
2018-01-05  0.204607 -0.335206  1.577587 -0.529661
2018-01-06  0.243641 -0.947076 -0.751013  1.203544
'''
# print(df2)
df3 = pd.DataFrame(
    {
        "A": 1.0,
        "B": pd.Timestamp("20130102" ),
        "C": pd.Series(1, index=list(range(4)), dtype="float32"),
        "D": np.array([3] * 4, dtype="int32"),
        "E": pd.Categorical(["test", "train", "test", "train"]),
        "F": "foo",
    }
)

# print(df3)
# print(df3.head)
# print(df.index)
# print(df.to_numpy())
# print(df3.dtypes)
# print(df3.describe())
# print(df3.T)
# print(df3.sort_index(axis=1 , ascending=False ))
# print(df3.sort_values(by="E"))
# print(df3["A"])
# print(df3[0:3])

left = pd.DataFrame({
    "key":["foo","foo"],
    "lval":[1,2]
})
right = pd.DataFrame({
    "key":["foo","bar"],
    "lval":[4,5]
})
# print(pd.merge(left, right, on="key"))
left1 = pd.DataFrame({
    "key":["foo","bar"],
    "lval":[1,2]
})
print(pd.merge(left1, right, on="key"))

df4 = pd.DataFrame({
    "A": ["foo" , "bar" ,"foo" , "bar" ,"foo" , "bar" ,"foo" , "bar" ] ,
    "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
    "C":np.random.randn(8),
    "D": np.random.randn(8) ,
})
# print(df4)
print(df4.groupby("A")[["C","D"]].sum())